import { Feature } from "ol";
import { createFeature } from "../create/createFeature";
import { createLineGeometry } from "../create/createGeometry";
import { createVectorLayer } from "../create/createLayer";
import { createSource } from "../create/createSource";
import { transform } from "ol/proj";
import {
  LineStyleOptions,
  // PointStyleOptions,
  createLineStyle,
} from "../styles/lineStyle";
import { transform4326to3857 } from "../utils/transform";
import { Coordinate } from "ol/coordinate";

type TransformType = typeof transform;
export interface CreateLineOptions {
  formaterLngLatFn?: (
    item: any,
    transform: TransformType
  ) => Array<[number, number]>;
  style?: LineStyleOptions;
}

export function createLineLayer<T>(data: T[], options?: CreateLineOptions) {
  const features: Feature[] = [];
  const { formaterLngLatFn = defaultFormaterLngLatFn } = options || {};
  data.forEach((item, index) => {
    const newPath = formaterLngLatFn(item, transform4326to3857);

    const feature = createFeature(createLineGeometry(newPath));
    const lineStyle = createLineStyle(options?.style);
    feature.setStyle(lineStyle);
    feature.set("data", item);

    features.push(feature);
  });

  const source = createSource();
  source.addFeatures(features);
  const layer = createVectorLayer({
    source,
  });
  return layer;
}

function defaultFormaterLngLatFn<T>(item: T, transform: any) {
  const path = item["path" as keyof T] as string;
  const pathArr = JSON.parse(path);
  let newPathArr: [number, number][] = [];
  for (let i = 0; i < pathArr.length; ) {
    newPathArr.push(transform([pathArr[i], pathArr[i + 1]]));
    i += 2;
  }
  return newPathArr;
}
